package com.younion.business.impl;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import com.google.common.collect.Maps;
import com.younion.business.ICostService;
import com.younion.common.constants.CostType;
import com.younion.common.exception.BusinessException;
import com.younion.common.paginator.Paginator;
import com.younion.dao.CostDAO;
import com.younion.dao.MemberCardDAO;
import com.younion.dao.ProductDAO;
import com.younion.dao.ScoreRuleDAO;
import com.younion.vo.CostVO;
import com.younion.vo.CustomerVO;
import com.younion.vo.MemberCardVO;

import cpcns.component.common.base.BaseException;
import cpcns.jhsks.util.MapCollectionUtils;

 
public class CostServiceImpl implements ICostService {

	protected static final Log logger = LogFactory.getLog(CostServiceImpl.class);

	private CostDAO costDAO;
	
	@Autowired
	private MemberCardDAO memberCardDAO;
	
	@Autowired
	private ProductDAO productDAO;
	@Autowired
	private ScoreRuleDAO ScoreRuleDAO;
	
	public Collection getAll() throws Exception {
		return costDAO.selectAll();
	}

	public CostVO getById(String id) throws Exception {
		if (StringUtils.isEmpty(id) || Integer.parseInt(id)<1)
			return null;
		try {
			Map paramMap = new HashMap();
			paramMap.put("id", new Integer(id));
			Object obj = costDAO.selectById(paramMap);
			return obj==null?null:(CostVO)obj;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new BaseException(CostServiceImpl.class.getName()+" >> public CostVO get(String id) error occur:",e);
		}
	}
	public Collection getByMap(Map paramMap) throws BaseException {
		if(CollectionUtils.isEmpty(paramMap)){
			return null;
		}
		try{
			return costDAO.selectByMap(paramMap);
		}catch(Exception e){
			logger.error(e.getMessage(), e);
			throw new BaseException(CostServiceImpl.class.getName()+" >> public Collection getByMap(Map map) error occur:",e);
		}
	}

	public int getCountByMap(Map paramMap) throws BaseException {
		try {
			return costDAO.selectCountByMap(paramMap);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new BaseException(CostServiceImpl.class.getName()
					+ " >> public Collection getCountByMap(Map map) error occur:", e);
		}
	}

	public List get(Map paramMap, Paginator paginator) throws Exception {
		if (MapCollectionUtils.isEmpty(paramMap)) {
			return null;
		}
		try {
			Map map = new HashMap();
			map.put("paramMap", paramMap);
			return costDAO.selectForPage(map, paginator);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new BaseException(CostServiceImpl.class.getName()+" >> public Page (Map paramMap, Paginator paginator) error occur:",e);
		}
	}

	public CostVO save(CostVO voObject) throws Exception {
		if (voObject == null)
			return null;
		Object id = null;
		id = voObject.getId();
		Map paramMap = MapCollectionUtils.removeEmptyEntry(PropertyUtils.describe(voObject));
		if (id != null) {
			costDAO.updateByMap(paramMap);
			return voObject;
		} else {
			Map memberCardParamMap = Maps.newHashMap();
			memberCardParamMap.put("id", voObject.getCardEntity().getId());
			MemberCardVO card = memberCardDAO.selectById(memberCardParamMap);
			voObject.setCustomer(new CustomerVO(card.getCustomerId()));
			MemberCardVO updateMemberCardParam = new MemberCardVO();
			updateMemberCardParam.setId(card.getId());
			//Map productParamMap = Maps.newHashMap();
			//productParamMap.put("id", voObject.getProduct().getId());
			//ProductVO product = productDAO.selectById(productParamMap);
			if(StringUtils.isBlank(voObject.getType())){
				throw new BusinessException("请选择消费类型！");
			}
			if(CostType.CASH.getName().equals(voObject.getType())){
				if(card.getCardBalance() == null || card.getCardBalance() < voObject.getMoney()){
					throw new BusinessException("对不起，您的余额不足！");
				}else{
					updateMemberCardParam.setCardBalance(card.getCardBalance() - Math.abs(voObject.getMoney().intValue()));
					updateMemberCardParam.setScore(card.getScore() + voObject.getScore().intValue());
					Map cardMap = MapCollectionUtils.removeEmptyEntry(PropertyUtils.describe(updateMemberCardParam));
					memberCardDAO.updateByMap(cardMap);
				}
			}else if (CostType.SCORE.getName().equals(voObject.getType())){
				if(card.getScore() == null || card.getScore() < voObject.getScore()){
					throw new BusinessException("对不起，您的积分不足！");
				}else{
					updateMemberCardParam.setScore(card.getScore() - Math.abs(voObject.getScore()));
					Map cardMap = MapCollectionUtils.removeEmptyEntry(PropertyUtils.describe(updateMemberCardParam));
					memberCardDAO.updateByMap(cardMap);
				}
			}else if (CostType.SAVING.getName().equals(voObject.getType())){
				if(card.getCardBalance() == null || card.getCardBalance() < voObject.getMoney()){
					throw new BusinessException("对不起，您的余额不足！");
				}else{
					updateMemberCardParam.setCardBalance(card.getCardBalance() - Math.abs(voObject.getMoney().intValue()));
					if(card.getScore() == null)
						card.setScore(0);
					if(voObject.getScore() != null){
						updateMemberCardParam.setScore(card.getScore() + voObject.getScore());
					}
					Map cardMap = MapCollectionUtils.removeEmptyEntry(PropertyUtils.describe(updateMemberCardParam));
					memberCardDAO.updateByMap(cardMap);
				}
			}else if (CostType.FEEDBACK.getName().equals(voObject.getType())){
				if(card.getScore() < voObject.getScore()){
					throw new BusinessException("对不起，您的积分不足，不能返销！");
				}else{
					updateMemberCardParam.setCardBalance(card.getCardBalance() + voObject.getMoney().intValue());
					updateMemberCardParam.setScore(card.getScore() - Math.abs(voObject.getScore()));
					Map cardMap = MapCollectionUtils.removeEmptyEntry(PropertyUtils.describe(updateMemberCardParam));
					voObject.setMoney(voObject.getMoney() * -1);
					voObject.setScore(voObject.getScore() * -1);
					memberCardDAO.updateByMap(cardMap);
				}
			}
			return (CostVO)costDAO.insertByVo(voObject);
		}
	}

	public Collection save(Collection voList) throws Exception {
		if (CollectionUtils.isEmpty(voList))
			return null;
		try {
			Iterator it = voList.iterator();
			while (it.hasNext()) {
				CostVO data = (CostVO) it.next();
				data = save(data);
			}
			return voList;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new BaseException(CostServiceImpl.class.getName()+" >> public Collection save(Collection voList) error occur:",e);
		}
	}

	public boolean remove(List ids) throws Exception {
		if (CollectionUtils.isEmpty(ids))
			return false;
		try{
			costDAO.deleteByIds(ids);
			return true;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new BaseException(CostServiceImpl.class.getName()+" >> public boolean remove(List ids) error occur:",e);
		}
	}

	public boolean removeByMap(Map paramMap) throws Exception {
		if (CollectionUtils.isEmpty(paramMap))
			return false;
		try {
			costDAO.deleteByMap(paramMap);
			return true;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new BaseException(CostServiceImpl.class.getName()+" >> public boolean removeByMap(Map paramMap) error occur:",e);
		}
	}
	/**
	 * @param service
	 */
	public void setCostDAO(CostDAO costDAO) {
		this.costDAO = costDAO;
	}

	public MemberCardDAO getMemberCardDAO() {
		return memberCardDAO;
	}

	public void setMemberCardDAO(MemberCardDAO memberCardDAO) {
		this.memberCardDAO = memberCardDAO;
	}

	public ProductDAO getProductDAO() {
		return productDAO;
	}

	public void setProductDAO(ProductDAO productDAO) {
		this.productDAO = productDAO;
	}

	public CostDAO getCostDAO() {
		return costDAO;
	}

	public ScoreRuleDAO getScoreRuleDAO() {
		return ScoreRuleDAO;
	}

	public void setScoreRuleDAO(ScoreRuleDAO scoreRuleDAO) {
		ScoreRuleDAO = scoreRuleDAO;
	}
	
	
	
}